<template>
    <div>
        <el-row :gutter="20" class="mgb20">
            <el-col v-for="(licence, index) in licences" :key="index" :span="6" @click="showLicenceInfo(licence)">
                <el-card shadow="hover" body-class="card-body">
                    <div :class="['card-icon1', getBgcolor()]">
                        <el-icon>
                            <User />
                        </el-icon>
                        <p>{{ licence.licenceType }}驾驶证</p>
                    </div>
                    <div class="card-content">
                        <countup class="card-num color1" :end="licence.licenceMoney" />
                        <div>
                            报名费用
                        </div>
                    </div>
                </el-card>
                <br>
            </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="7">
                <el-card shadow="hover" :body-style="{ height: '400px' }">
                    <div class="card-header">
                        <div class="study-card-header">
                            <div>
                                <p class="card-header-title">学习进度</p>
                                <p class="card-header-desc">驾驶证学习动态与信息</p>
                            </div>
                            <div>
                                <el-button size="large" @click="gotoStudyProgress()">查看详情</el-button>
                            </div>
                        </div>

                    </div>
                    <el-timeline>
                        <el-timeline-item v-for="(activity, index) in activities" :key="index" :color="activity.color">
                            <div class="timeline-item">
                                <div>
                                    <p>{{ activity.title }}</p>
                                    <p class="timeline-desc">{{ activity.content }}</p>
                                </div>
                                <div class="timeline-time">{{ activity.date }}</div>
                            </div>
                        </el-timeline-item>
                    </el-timeline>
                </el-card>
            </el-col>
            <el-col :span="10">
                <el-card shadow="hover" :body-style="{ height: '400px' }">
                    <div class="card-header study-card-header">
                        <div>
                            <p class="card-header-title">考试成绩</p>
                            <p class="card-header-desc">驾驶证的考试记录</p>
                        </div>
                        <div>
                            <el-button size="large" @click="gotoExam()">查看详情</el-button>
                        </div>
                    </div>
                    <div>
                        <el-table :data="tableData" style="width: 100%;  height: 400px; overflow-y: auto;">
                            <el-table-column prop="subject" label="考试科目" width="120" show-overflow-tooltip />
                            <el-table-column prop="grade" label="成绩" width="120" show-overflow-tooltip />
                            <el-table-column prop="date" label="考试时间" show-overflow-tooltip />
                        </el-table>
                    </div>

                </el-card>
            </el-col>
            <el-col :span="7">
                <el-card shadow="hover" :body-style="{ height: '400px' }">
                    <div class="card-header">
                        <p class="card-header-title">排行榜</p>
                        <p class="card-header-desc">驾驶证报名热门Top4</p>
                    </div>
                    <div class="rank-card-body">
                        <div class="rank-item" v-for="(rank, index) in ranks" :key="index">
                            <div class="rank-item-avatar">{{ index + 1 }}</div>
                            <div v-if="rank.value != null" class="rank-item-content">
                                <div class="rank-item-top">
                                    <div class="rank-item-title">{{ rank.key + "驾驶证" }}</div>
                                    <div class="rank-item-desc">报考热度：{{ rank.value }}</div>
                                </div>
                                <w-rating v-model="rank.value" readonly class="my2" color="light-green">
                                </w-rating>
                            </div>
                            <div v-else>
                                <w-alert class="grow ma2" color="primary" border-left>
                                    暂无数据
                                </w-alert>
                            </div>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
    <w-dialog v-model="dialog.show" :fullscreen="dialog.fullscreen" :width="dialog.width"
        :persistent="dialog.persistent" :persistent-no-animation="dialog.persistentNoAnimation"
        title-class="primary-light1--bg white">
        <template #title>
            <el-icon>
                <InfoFilled />
            </el-icon>
            {{ dialog.title }}
        </template>
        <w-card>
            <p class="content">{{ dialog.content }}</p>
        </w-card>
        <template #actions>
            <div class="spacer" />
            <w-button @click="dialog.show = false">关闭</w-button>
        </template>
    </w-dialog>
</template>

<script setup lang="ts" name="dashboard">
import { ref, reactive } from 'vue';
import countup from '@/components/countup.vue';
import { use, registerMap } from 'echarts/core';
import { BarChart, LineChart, PieChart, MapChart } from 'echarts/charts';
import {
    GridComponent,
    TooltipComponent,
    LegendComponent,
    TitleComponent,
    VisualMapComponent,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import VChart from 'vue-echarts';
import chinaMap from '@/utils/china';
import * as studentApi from '@/api/student';
import * as licenceApi from '@/api/licence';
import * as processApi from '@/api/process';
import * as examApi from '@/api/exam';
import router from '@/router';
use([
    CanvasRenderer,
    BarChart,
    GridComponent,
    LineChart,
    PieChart,
    TooltipComponent,
    LegendComponent,
    TitleComponent,
    VisualMapComponent,
    MapChart,
]);
registerMap('china', chinaMap);


//
const role = localStorage.getItem('vuems_name');
const studentId = ref();
const dialog = ref({
    show: false,
    fullscreen: false,
    persistent: false,
    persistentNoAnimation: false,
    width: 500,
    title: '',
    content: '',
})

//驾驶证相关
const licences = ref();
const getLicenceInfo = async () => {
    const response = await licenceApi.getAllLicence();
    licences.value = response.data.data.getAllLicence;
}
const showLicenceInfo = (licence) => {
    dialog.value.show = true;
    dialog.value.title = licence.licenceType + '驾驶证报考注意事项';
    dialog.value.content = licence.licenceText;
}
const getBgcolor = () => {
    return 'bg' + (Math.floor(Math.random() * 8) + 1);
}

//排行榜相关
const ranks = ref();
const getRanksInfo = async () => {
    const response = await licenceApi.findHotLicence();
    let rs = response.data.data.findHotLicence;
    let tempRanks = [];
    for (let i = 0; i < rs.length; i++) {
        let key = Object.keys(rs[i])[0];
        let value = rs[i][key];
        Number(value.toFixed(2))
        tempRanks.push({ key: key, value: Number(value.toFixed(2)) });
    }
    ranks.value = tempRanks;
}

//考试成绩与学校进度相关
const tableData = ref();
const activities = ref();
const getRandomColor = () =>{
  const letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}
const formatteDate = (dateValue) => {
    let year = dateValue.getFullYear();
    let month = dateValue.getMonth() + 1; // 获取月份，+1 是因为 getMonth() 返回的月份是从0开始的
    let day = dateValue.getDate();
    // 确保月份和日期始终是两位数的格式
    month = month < 10 ? '0' + month : month;
    day = day < 10 ? '0' + day : day;
    let formattedDate = `${year}-${month}-${day}`;
    return formattedDate;
}
const generateContent = (times) => {
    if (times === 1) {
        return "真厉害！第" + times + "次就通过了考试。";
    }else if (times === 0) {
        return "坚持练习，驾照很快就到手";
    } else if (times < 4) {
        return "太棒了！只用了" + times + "次就成功了。";
    } else {
        return "这是第" + times + "次尝试。";
    }
}
const getProcess = async () => {
    const response = await processApi.findApplicationAndExam(studentId.value);
    let rs = response.data.data.findApplicationAndExam;
    let parsedData = [];
    // 遍历对象的每个键值对
    for (let key in rs) {
        if (rs.hasOwnProperty(key)) {
            // 处理键：去除花括号并分割字符串以获取实际的键和值
            let trimmedKey = key.replace(/[{}]/g, ''); // 去除花括号
            let [mapKey, mapValue] = trimmedKey.split('='); // 分割字符串
            let dateValue = new Date(rs[key]);
            const regex = /^[A-Z]\d$/;
            if(regex.test(mapKey)) mapKey = "开始"+mapKey+"驾驶证的学习";
            else mapKey = mapKey+"考试";
            parsedData.push({ title: mapKey, content: generateContent(parseInt(mapValue)), date: formatteDate(dateValue) ,color : getRandomColor()});
        }
    }
    activities.value = parsedData;
}
const getGrades = async () => {
    const response = await examApi.findByStudentID(studentId.value);
    let rs = response.data.data.getExam;
    let t = [];
    rs.forEach(element => {
        t.push({subject : element.subject.subjectType , date : formatteDate(new Date(element.examTime)) , grade : element.examScore})
    });
    tableData.value = t;
}


//总初始化
const init = () => {
    console.log(role);
    console.log(localStorage.getItem("studnetAccountId"));
    studentId.value = JSON.parse(localStorage.getItem('studentInfo')).studentId;
    console.log(studentId.value);
    getLicenceInfo();
    getRanksInfo();
    getProcess();
    getGrades();
    // let keys = Object.keys(localStorage);
    // for (let i = 0; i < keys.length; i++) {
    //     console.log(`Key: ${keys[i]}, Value: ${localStorage.getItem(keys[i])}`);
    // }
}

//路由跳转
const gotoStudyProgress = () => {
    router.push("/studyProcess");
}
const gotoExam = () => {
    router.push("/exam");
}
init();
</script>

<style>
.card-body {
    display: flex;
    align-items: center;
    height: 150px;
    padding: 0;
}
</style>
<style scoped>
.card-content {
    flex: 1;
    text-align: center;
    font-size: 18px;
    color: #999;
    padding: 0 20px;
}

.card-num {
    font-size: 30px;
}

.card-icon {
    font-size: 50px;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
    color: #fff;
}

.bg1 {
    background: #2d8cf0;
}

.bg2 {
    background: #64d572;
}

.bg3 {
    background: #f25e43;
}

.bg4 {
    background: #e9a745;
}

.bg5 {
    background: #FF2400;
    /* 猩红色 */
}

.bg6 {
    background: #0047AB;
    /* 钴蓝色 */
}

.bg7 {
    background: #800080;
    /* 紫色 */
}

.bg8 {
    background: #E62020;
    /* 激情红 */
}


.color1 {
    color: #2d8cf0;
}

.color2 {
    color: #64d572;
}

.color3 {
    color: #f25e43;
}

.color4 {
    color: #e9a745;
}

.chart {
    width: 100%;
    height: 400px;
}

.card-header {
    padding-left: 10px;
    margin-bottom: 20px;
}

.card-header-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 5px;
}

.card-header-desc {
    font-size: 14px;
    color: #999;
}

.timeline-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    color: #000;
}

.timeline-time,
.timeline-desc {
    font-size: 12px;
    color: #787878;
}

.rank-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.rank-item-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #f2f2f2;
    text-align: center;
    line-height: 40px;
    margin-right: 10px;
}

.rank-item-content {
    flex: 1;
}

.rank-item-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #343434;
    /* margin-bottom: 1px; */
}

.rank-item-desc {
    font-size: 14px;
    color: #999;
}

.map-chart {
    width: 100%;
    height: 350px;
}




.card-icon1 {

    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 100px;
    border: 1px solid #ddd;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-icon1 .el-icon {
    font-size: 40px;
    color: #fff;
}

.card-icon1 p {
    margin-top: 10px;
    font-size: 14px;
    color: #fff;
}

.content {
    white-space: pre-wrap;
    /* CSS3 */
    white-space: -moz-pre-wrap;
    /* Firefox */
    white-space: -pre-wrap;
    /* Opera <7 */
    white-space: -o-pre-wrap;
    /* Opera 7 */
    word-wrap: break-word;
    /* IE */
}

.rank-card-body {
    height: 350px;
    overflow-y: auto;
    flex: 1;
}

.study-card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>
